package com.zg.assistant.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zg.assistant.req.FormFieldReq;
import com.zg.assistant.req.ImageRecognitionReq;
import com.zg.assistant.service.ImageRecognitionService;
import com.zg.common.core.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 图片识别服务实现类
 * @author zg
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ImageRecognitionServiceImpl implements ImageRecognitionService {

    private final RestTemplate restTemplate;

    @Value("${aliyun.apiKey:sk-1e3e9eeef9434d2c8fba3d2646bf9e8f}")
    private String apiKey;

    @Value("${aliyun.apiUrl:https://dashscope.aliyuncs.com/compatible-mode/v1}")
    private String apiUrl;

    @Value("${aliyun.model:qwen-vl-max}")
    private String modelName;

    @Override
    public Map<String, Object> imageRecognition(ImageRecognitionReq imageRecognitionReq) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            // 获取图片URL和表单数据
            String imageUrl = imageRecognitionReq.getImageUrl();
            List<FormFieldReq> formFields = imageRecognitionReq.getFormFields();

            // 构建询问语句
            String question = buildDefaultQuestion(formFields);

            // 构建请求体
            Map<String, Object> requestBody = buildRequestBody(imageUrl, question);

            // 发送请求
            String url = apiUrl + "/chat/completions";
            log.info("发送图片识别请求: URL={}, Body={}", url, JSON.toJSONString(requestBody));

            // 使用Hutool发送HTTP请求
            HttpResponse response = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .body(JSON.toJSONString(requestBody))
                .execute();

            if (response.getStatus() == HttpStatus.HTTP_OK) {
                String responseBody = response.body();
                log.info("图片识别响应: {}", responseBody);

                JSONObject jsonResponse = JSON.parseObject(responseBody);

                // 提取响应内容
                String contentText = extractContentText(jsonResponse);
                log.info("提取的内容: {}", contentText);

                // 处理响应内容，转换为结构化数据
                resultMap = processResponseContent(contentText, formFields);

                return resultMap;
            } else {
                log.error("图片识别请求失败: {}", response.body());
                BusinessException.happen("请求失败: " + response.getStatus());
            }
        } catch (Exception e) {
            log.error("图片识别处理异常", e);
            BusinessException.happen("处理异常: " + e.getMessage());
        }
        return resultMap;
    }

    /**
     * 构建请求体
     */
    private Map<String, Object> buildRequestBody(String imageUrl, String question) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", modelName);

        List<Map<String, Object>> messages = new ArrayList<>();
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");

        List<Map<String, Object>> content = new ArrayList<>();

        // 添加图片
        Map<String, Object> imageContent = new HashMap<>();
        imageContent.put("type", "image_url");

        Map<String, String> imageUrlMap = new HashMap<>();
        imageUrlMap.put("url", imageUrl);

        imageContent.put("image_url", imageUrlMap);
        content.add(imageContent);

        // 添加文本
        Map<String, Object> textContent = new HashMap<>();
        textContent.put("type", "text");
        textContent.put("text", question);
        content.add(textContent);

        message.put("content", content);
        messages.add(message);
        requestBody.put("messages", messages);

        return requestBody;
    }

    /**
     * 从响应中提取文本内容
     */
    private String extractContentText(JSONObject jsonResponse) {
        try {
            JSONArray choices = jsonResponse.getJSONArray("choices");
            if (choices != null && !choices.isEmpty()) {
                JSONObject firstChoice = choices.getJSONObject(0);
                JSONObject message = firstChoice.getJSONObject("message");
                if (message != null) {
                    String content = message.getString("content");
                    // 去除可能存在的Markdown代码块标记
                    return cleanMarkdownCodeBlocks(content);
                }
            }
        } catch (Exception e) {
            log.error("提取响应内容失败", e);
        }
        return "";
    }

    /**
     * 清理Markdown代码块标记
     */
    private String cleanMarkdownCodeBlocks(String content) {
        if (content == null) {
            return "";
        }

        // 移除Markdown的JSON代码块标记 ```json 和 ```
        return content.replaceAll("```json\\s*", "").replaceAll("```\\s*", "");
    }

    /**
     * 处理响应内容，转换为结构化数据
     */
    private Map<String, Object> processResponseContent(String content, List<FormFieldReq> formFields) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 尝试直接解析JSON
            if (content.contains("{") && content.contains("}")) {
                // 提取JSON字符串
                Pattern pattern = Pattern.compile("\\{[\\s\\S]*\\}");
                Matcher matcher = pattern.matcher(content);
                if (matcher.find()) {
                    String jsonStr = matcher.group();
                    try {
                        JSONObject jsonObject = JSON.parseObject(jsonStr);

                        // 如果提供了字段映射，进行转换
                        if (formFields != null && !formFields.isEmpty()) {
                            for (FormFieldReq field : formFields) {
                                String name = field.getName();
                                String label = field.getLabel();
                                if (jsonObject.containsKey(label)) {
                                    // 优先使用label作为键
                                    result.put(label, jsonObject.get(label));
                                } else if (jsonObject.containsKey(name)) {
                                    // 如果label不存在，尝试使用name作为键
                                    result.put(label, jsonObject.get(name));
                                }
                            }
                            // 如果没有找到任何匹配字段，直接返回原始JSON
                            if (result.isEmpty()) {
                                return new HashMap<>(jsonObject);
                            }
                            return result;
                        } else {
                            // 直接返回解析的JSON
                            return new HashMap<>(jsonObject);
                        }
                    } catch (Exception e) {
                        log.warn("JSON解析失败，尝试使用正则表达式提取: {}", e.getMessage());
                    }
                }
            }

            // 如果无法解析JSON，尝试从文本中提取键值对
            if (formFields != null && !formFields.isEmpty()) {
                for (FormFieldReq field : formFields) {
                    String name = field.getName();
                    String label = field.getLabel();

                    // 尝试匹配 "name: value" 或 "name：value" 模式
                    Pattern pattern = Pattern.compile(name + "[：:](.*?)(?=\\n|$|，|。|、|；|;|,)");
                    Matcher matcher = pattern.matcher(content);
                    if (matcher.find()) {
                        String value = matcher.group(1).trim();
                        result.put(label, value);
                    }
                }
            }
        } catch (Exception e) {
            log.error("处理响应内容失败", e);
        }

        return result;
    }

    /**
     * 构建默认问题
     */
    private String buildDefaultQuestion(List<FormFieldReq> formFields) {
        StringBuilder question = new StringBuilder("请依据图片内容识别以下信息：");
        StringBuilder jsonFields = new StringBuilder("[");

        for (int i = 0; i < formFields.size(); i++) {
            FormFieldReq field = formFields.get(i);
            String name = field.getName();
            String label = field.getLabel();

            // 添加到问题描述
            question.append(name);
            if (i < formFields.size() - 1) {
                question.append("、");
            }

            // 添加到JSON字段描述
            jsonFields.append("{\"name\": \"").append(name).append("\", \"label\": \"").append(label).append("\"}");
            if (i < formFields.size() - 1) {
                jsonFields.append(", ");
            }
        }

        jsonFields.append("]");
        question.append("。请依据图片内容及我提供的表单 JSON：").append(jsonFields)
               .append("，识别并转换为目标 JSON。仅输出最终的 JSON 内容，无需其他多余信息。");

        return question.toString();
    }
}
